package com.example.hosptial.service.impl;

import com.example.hosptial.model.enity.Bed;
import com.example.hosptial.model.enity.Ward;
import com.example.hosptial.model.view.WardBedPatientView;
import com.example.hosptial.model.view.WardStatusView;
import com.example.hosptial.repository.BedRepository;
import com.example.hosptial.repository.WardRepository;
import com.example.hosptial.repository.WardStatusRepository;
import com.example.hosptial.repository.WardBedPatientViewRepository;
import com.example.hosptial.repository.NurseWardAssignmentRepository;
import com.example.hosptial.model.enity.Nurse;
import com.example.hosptial.model.enity.NurseWardAssignment;
import com.example.hosptial.service.BedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class BedServiceImpl implements BedService {
    private static final Logger logger = LoggerFactory.getLogger(BedServiceImpl.class);

    @Autowired
    private BedRepository bedRepository;

    @Autowired
    private WardRepository wardRepository;

    @Autowired
    private WardStatusRepository wardStatusRepository;

    @Autowired
    private WardBedPatientViewRepository wardBedPatientViewRepository;

    @Autowired
    private NurseWardAssignmentRepository nurseWardAssignmentRepository;

    @Override
    @Transactional
    public Bed addBed(Integer wardId) {
        // 参数验证
        if (wardId == null || wardId <= 0) {
            throw new IllegalArgumentException("无效的病房ID");
        }

        // 检查病房是否存在
        Ward ward = wardRepository.findById(wardId)
            .orElseThrow(() -> new IllegalArgumentException("病房不存在"));

        try {
            // 调用存储过程添加床位
            bedRepository.addBed(wardId);
            
            // 获取新添加的床位（查询最后一个添加的床位）
            List<Bed> wardBeds = bedRepository.findByWardWardIdOrderByBedNum(wardId);
            if (wardBeds.isEmpty()) {
                throw new RuntimeException("添加床位失败：无法获取新床位信息");
            }
            return wardBeds.get(wardBeds.size() - 1);
            
        } catch (Exception e) {
            logger.error("添加床位时发生错误: {}", e.getMessage());
            throw new RuntimeException("添加床位失败: " + e.getMessage());
        }
    }

    @Override
    public List<Bed> getWardBeds(Integer wardId) {
        if (wardId == null || wardId <= 0) {
            throw new IllegalArgumentException("无效的病房ID");
        }

        // 检查病房是否存在
        if (!wardRepository.existsById(wardId)) {
            throw new IllegalArgumentException("病房不存在");
        }

        return bedRepository.findByWardWardIdOrderByBedNum(wardId);
    }

    @Override
    public List<Bed> getAvailableBeds() {
        return bedRepository.findByBedStatus(2); // 2表示空闲
    }

    @Override
    @Transactional
    public void updateBedStatus(Integer bedId, Integer status) {
        if (bedId == null || bedId <= 0) {
            throw new IllegalArgumentException("无效的床位ID");
        }
        if (status != 1 && status != 2) {
            throw new IllegalArgumentException("无效的床位状态");
        }

        bedRepository.updateBedStatus(bedId, status);
    }

    @Override
    public List<Map<String, Object>> getWardsByDepartment(Integer deptId) {
        List<WardStatusView> wards;
        if (deptId != null) {
            wards = wardStatusRepository.findByDeptIdOrderByFloorNumAscWardNumAsc(deptId);
        } else {
            wards = wardStatusRepository.findAll();
        }

        List<Map<String, Object>> result = new ArrayList<>();
        for (WardStatusView ward : wards) {
            Map<String, Object> wardMap = new HashMap<>();
            wardMap.put("wardId", ward.getWardId());
            wardMap.put("deptName", ward.getDeptName());
            wardMap.put("floorNum", ward.getFloorNum());
            wardMap.put("wardNum", ward.getWardNum());
            wardMap.put("bedCount", ward.getBedCount());
            wardMap.put("availableBeds", ward.getAvailableBeds());
            result.add(wardMap);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getWardBedDetails(Integer wardId) {
        if (wardId == null || wardId <= 0) {
            throw new IllegalArgumentException("无效的病房ID");
        }

        List<WardBedPatientView> beds = wardBedPatientViewRepository.findByWardIdOrderByBedNum(wardId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (WardBedPatientView bed : beds) {
            Map<String, Object> bedMap = new HashMap<>();
            bedMap.put("bedId", bed.getBedId());
            bedMap.put("bedNum", bed.getBedNum());
            bedMap.put("status", bed.getBedStatus());
            bedMap.put("patientId", bed.getPatientId());
            bedMap.put("patientName", bed.getPatientName());
            result.add(bedMap);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getWardNurses(Integer wardId) {
        if (wardId == null || wardId <= 0) {
            throw new IllegalArgumentException("无效的病房ID");
        }

        List<NurseWardAssignment> assignments = nurseWardAssignmentRepository.findByWardWardId(wardId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (NurseWardAssignment assignment : assignments) {
            Map<String, Object> nurseMap = new HashMap<>();
            Nurse nurse = assignment.getNurse();
            nurseMap.put("nurseId", nurse.getNurseId());
            nurseMap.put("nurseName", nurse.getNurseName());
            nurseMap.put("nurseGender", nurse.getNurseGender());
            nurseMap.put("nursePhone", nurse.getNursePhone());
            result.add(nurseMap);
        }

        return result;
    }
}